package com.xijia.wuyouwallet.activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.xijia.wuyouwallet.MyApp;
import com.xijia.wuyouwallet.R;
import com.xijia.wuyouwallet.adapter.CreditcardRefundAdapter;
import com.xijia.wuyouwallet.api.MyCallBack;
import com.xijia.wuyouwallet.base.BaseActivity;
import com.xijia.wuyouwallet.bean.RefundData;
import com.xijia.wuyouwallet.bean.WistRefundData;
import com.xijia.wuyouwallet.utils.Constants;
import com.xijia.wuyouwallet.utils.MyLogger;
import com.xijia.wuyouwallet.utils.UrlConfig;
import com.xijia.wuyouwallet.utils.XUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/1 0001.
 */

public class CreditcardRefundACtivity extends BaseActivity implements View.OnClickListener,CreditcardRefundAdapter.reFundCallBack{

    private ImageView refund_back,refund_cardImg;
    private TextView refund_meRefundTv,refund_nestStep;
    private ListView refund_lv;

    private Dialog fillBankDialog;
    private TextView dialog_fillBank_billTime,dialog_fillBank_refundTime;

    private List<RefundData> list = new ArrayList<>();
    private CreditcardRefundAdapter mAdapter;

    Calendar calendar = Calendar.getInstance();

    private String card_img=null;
    private String card_name=null;
    private String card_num=null;

    private String card_id=null;
    private String repay_pay_money=null;
    private String repay_have_money=null;
    private String repay_start_time=null;
    private String repay_end_time=null;

    private int postation;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_creditcards_refund);
        initView();
    }
    private void initView(){
        refund_back = (ImageView) findViewById(R.id.refund_back);
        refund_back.setOnClickListener(this);
        refund_cardImg = (ImageView) findViewById(R.id.refund_cardImg);
        refund_cardImg.setOnClickListener(this);
        refund_meRefundTv = (TextView) findViewById(R.id.refund_meRefundTv);
        refund_meRefundTv.setOnClickListener(this);
        refund_nestStep = (TextView) findViewById(R.id.refund_nestStep);
        refund_nestStep.setOnClickListener(this);
        refund_lv = (ListView) findViewById(R.id.refund_lv);

        mAdapter = new CreditcardRefundAdapter(list,this,this);
        refund_lv.setAdapter(mAdapter);

        //initfillBankDialog();
    }
    /**
     *
     */
    private void initfillBankDialog(final boolean isUp){
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_fill_bank_message, null);
        final EditText dialog_fillBank_refundMoney = (EditText) view.findViewById(R.id.dialog_fillBank_refundMoney);
        final EditText dialog_fillBank_usedMoney = (EditText) view.findViewById(R.id.dialog_fillBank_usedMoney);
        dialog_fillBank_billTime = (TextView) view.findViewById(R.id.dialog_fillBank_billTime);
        dialog_fillBank_billTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initDataPicker("1");
            }
        });
        dialog_fillBank_refundTime = (TextView) view.findViewById(R.id.dialog_fillBank_refundTime);
        dialog_fillBank_refundTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initDataPicker("2");
            }
        });
        TextView dialog_fillBank_config = (TextView) view.findViewById(R.id.dialog_fillBank_config);
        dialog_fillBank_config.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                repay_pay_money = dialog_fillBank_refundMoney.getText().toString();
                if (repay_pay_money.isEmpty()){
                    showToast("请输入还款金额");
                    return;
                }
                repay_have_money = dialog_fillBank_usedMoney.getText().toString();
                if (repay_have_money.isEmpty()){
                    showToast("请输入还款金额");
                    return;
                }
                if (repay_start_time==null){
                    showToast("请选择账单日");
                    return;
                }
                if (repay_end_time==null){
                    showToast("请选择还款日");
                    return;
                }
                MyLogger.wLog().e("card_img ="+card_img);
                MyLogger.wLog().e("card_num ="+card_num);
                MyLogger.wLog().e("card_name ="+card_name);
                MyLogger.wLog().e("card_id ="+card_id);
                MyLogger.wLog().e("repay_pay_money ="+repay_pay_money);
                MyLogger.wLog().e("repay_have_money ="+repay_have_money);
                MyLogger.wLog().e("repay_end_time ="+repay_end_time);
                MyLogger.wLog().e("repay_start_time ="+repay_start_time);
                if (!isUp){
                    list.add(new RefundData(card_img,card_num,card_name,card_id,repay_pay_money,repay_have_money,repay_start_time,repay_end_time));
                }else {
                    list.get(postation).setRepay_pay_money(repay_pay_money);
                    list.get(postation).setRepay_have_money(repay_have_money);
                    list.get(postation).setRepay_start_time(repay_start_time);
                    list.get(postation).setRepay_end_time(repay_end_time);
                }
                mAdapter.notifyDataSetChanged();
                fillBankDialog.dismiss();
            }
        });
        if (isUp){
            dialog_fillBank_refundMoney.setText(list.get(postation).getRepay_pay_money());
            dialog_fillBank_usedMoney.setText(list.get(postation).getRepay_have_money());
            dialog_fillBank_billTime.setText(list.get(postation).getRepay_start_time());
            dialog_fillBank_refundTime.setText(list.get(postation).getRepay_end_time());
        }
        fillBankDialog = new Dialog(this, R.style.ShopbagDialogStyle);
        fillBankDialog.setContentView(view);
        fillBankDialog.show();
    }
    /**
     * 日期选择
     *
     * @param timeType
     */
    private void initDataPicker(final String timeType){
        //自定义控件
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_date_picker, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        //设置日期简略显示 否则详细显示 包括:星期\周
        datePicker.setCalendarViewShown(false);
        //初始化当前日期
        calendar.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), null);
        //设置date布局
        builder.setView(view);
        builder.setTitle("设置日期信息");
        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //日期格式
                StringBuffer sb = new StringBuffer();
                sb.append(String.format("%d-%02d-%02d",
                        datePicker.getYear(),
                        datePicker.getMonth() + 1,
                        datePicker.getDayOfMonth()));
                MyLogger.wLog().e("datePicker.getYear()="+datePicker.getYear());
                MyLogger.wLog().e("datePicker.getMonth()="+datePicker.getMonth());
                MyLogger.wLog().e("datePicker.getDayOfMonth()="+datePicker.getDayOfMonth());
                MyLogger.wLog().e("sb.tostring()="+sb.toString());
                if (timeType.equals("1")){
                    repay_start_time = sb.toString();
                    dialog_fillBank_billTime.setText(repay_start_time);
                }else if (timeType.equals("2")){
                    repay_end_time = sb.toString();
                    dialog_fillBank_refundTime.setText(repay_end_time);
                }
                 //oplandate.setText(sb);
                 //赋值后面闹钟使用
                 //mYear = datePicker.getYear();
                 //mMonth = datePicker.getMonth();
                 //mDay = datePicker.getDayOfMonth();
                dialog.cancel();
            }
        });
        builder.setNegativeButton("取  消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.create().show();
    }
    /**
     * refund Money
     */
    private void requestRefundData(){
        Map<String,Object> map = new HashMap<>();
        map.put("token",MyApp.userData.getData().getToken());
        map.put("user",MyApp.userData.getData().getUser_id());
        map.put("data",creatJson());
        MyLogger.wLog().e("token="+MyApp.userData.getData().getToken());
        MyLogger.wLog().e("user="+MyApp.userData.getData().getUser_id());
        MyLogger.wLog().e("creatJson="+creatJson());
        XUtil.Post(UrlConfig.ADD_PLAN_CARD_URL,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                MyLogger.wLog().e("ADD_PLAN_CARD result="+result);
                WistRefundData data = com.alibaba.fastjson.JSONObject.parseObject(result,WistRefundData.class);
                if (data.getCode()==200){
                    Bundle bundle = new Bundle();
                    String url = UrlConfig.WISTE_REFUND_URL+"/sign/"+data.getData().getRepay_plan_sign()
                            +"/user/"+MyApp.userData.getData().getUser_id();
                    bundle.putString("url",url);
                    //jumpToPage(.class,bundle);
                    //jumpToPage(PayWvActivity.class,bundle);
                    jumpToPage(PayWvActivity.class,bundle,true, Constants.REQUEST_DATA_THREE,false);
                }else {
                    showToast(data.getMsg());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                showToast("服务器错误。。。");
                MyLogger.wLog().e("ADD_PLAN_CARD onError="+ex.toString());
            }
        });
    }
    /**
     * creat json
     *
     * @return
     */
    private String creatJson(){

        String jsonresult = "";//定义返回字符串
        JSONArray jsonarray = null;
        JSONObject object = new JSONObject();//创建一个总的对象，这个对象对整个json串
        try {
            jsonarray = new JSONArray();
        for (int i = 0;i < list.size();i++){
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("card_id", list.get(i).getCard_id());//向pet对象里面添加值
            jsonObj.put("repay_pay_money", list.get(i).getRepay_pay_money());
            jsonObj.put("repay_have_money", list.get(i).getRepay_have_money());
            jsonObj.put("repay_start_time", list.get(i).getRepay_start_time());
            jsonObj.put("repay_end_time", list.get(i).getRepay_end_time());
            jsonarray.put(jsonObj);
        }
            object.put("data",jsonarray);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            MyLogger.wLog().e("创建json 失败");
        }
        /*try {
            jsonresult = object.getJSONArray("data").toString();//生成返回字符串
        } catch (JSONException e) {
            e.printStackTrace();
        }*/
        return jsonarray.toString();

    }

    @Override
    public void onClick(View view) {
        Bundle bundle = null;
        switch (view.getId()){
            case R.id.refund_back:
                finish();
                break;
            case R.id.refund_meRefundTv://我的代理
                bundle = new Bundle();
                bundle.putString("url",UrlConfig.WISTE_ME_REFUND_URL+"/user/"+MyApp.userData.getData().getUser_id());
                jumpToPage(CommonWvActivity.class,bundle);
                break;
            case R.id.refund_nestStep://下一步
                if (!list.isEmpty()){
                    requestRefundData();
                }else {
                    showToast("请选择银行卡");
                    return;
                }
                break;
            case R.id.refund_cardImg://选择银行卡
                MyApp.isRefund = true;
                bundle = new Bundle();
                bundle.putString("cardType","0");
                jumpToPage(ChoiceBankActivity.class,bundle,true, Constants.REQUEST_DATA,false);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==Constants.REQUEST_DATA&&resultCode==Constants.RESULT_DATA){
            card_img = data.getStringExtra("img");
            card_name = data.getStringExtra("name");
            card_num = data.getStringExtra("num");
            card_id = data.getStringExtra("cardId");
            initfillBankDialog(false);
        }else if (requestCode==Constants.REQUEST_DATA_THREE&&resultCode==Constants.RESULT_DATA){
            CreditcardRefundACtivity.this.finish();
        }
    }

    //======================================
    @Override
    public void delect(int postion, String type) {
        if (type.equals("1")){
            this.postation = postion;
            initfillBankDialog(true);
        }else if (type.equals("2")){
            list.remove(postion);
            mAdapter.notifyDataSetChanged();
        }
    }
}
